package com.xoms.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.xoms.admin.controller.res.ListResult;
import com.xoms.admin.controller.res.bean.*;
import com.xoms.admin.controller.springmvc.req.GetDimePriceDetailParam;
import com.xoms.admin.controller.springmvc.req.GetRoomListParam;
import com.xoms.admin.controller.springmvc.req.GetRoomMonthPriceParam;
import com.xoms.admin.controller.springmvc.req.GetRoomPriceDetailParam;
import com.xoms.admin.model.*;
import com.xoms.admin.persist.dao.RoomDao;
import com.xoms.admin.service.RoomService;
import com.xoms.admin.service.exception.ServiceException;
import com.xoms.admin.service.res.PageResult;
import com.xoms.util.AppTextUtil;
import com.xoms.util.DateTimeUtil;
import com.xoms.util.NumUtil;
import com.xoms.util.StringUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: tzz(Tian)
 * Date: 2018/4/28 12:33
 */

@Service
public class RoomServiceImpl implements RoomService {
    Logger logger = Logger.getLogger(this.getClass());

    @Autowired
    RoomDao roomImpl;

    @Override
    public PageResult<RRoomDimensionBean> getRoomDimensions() {
        PageResult<RRoomDimensionBean> result = new PageResult<RRoomDimensionBean>();
        List<RoomDimensionBean> resultList = roomImpl.selectDimensions();
        List<RRoomDimensionBean> resList = new ArrayList<RRoomDimensionBean>();
        if (resultList != null) {
            RRoomDimensionBean rar = null;
            for (RoomDimensionBean res : resultList) {
                rar = new RRoomDimensionBean();

                BeanUtils.copyProperties(res, rar);
                resList.add(rar);
            }
        }
        result.setData(resList);
        result.setCount(resList.size());

        return result;
    }

    @Override
    public ListResult<RRoomDimensionDetailBean> getDimensionDetails(String dimensionId) {
        ListResult<RRoomDimensionDetailBean> result = new ListResult<RRoomDimensionDetailBean>();
        List<RRoomDimensionDetailBean> resList = new ArrayList<RRoomDimensionDetailBean>();
        List<RoomDimensionDetailBean> lists = roomImpl.getDimensionDetailList(dimensionId);
        if (lists != null) {
            RRoomDimensionDetailBean rar = null;
            for (RoomDimensionDetailBean res : lists) {
                rar = new RRoomDimensionDetailBean();

                BeanUtils.copyProperties(res, rar);
                rar.setCreateTime(DateTimeUtil.formatTimestamp(res.getCreateTime()));
                resList.add(rar);
            }
        }
        result.setData(resList);
        result.setTotalSize(resList.size());
        return result;
    }


    @Override
    public ListResult<RRoomDimensionDetailBean> getDimensionAllDetail() {
        ListResult<RRoomDimensionDetailBean> result = new ListResult<RRoomDimensionDetailBean>();
        List<RRoomDimensionDetailBean> resList = roomImpl.getDimensionAllDetailList();
        result.setData(resList);
        result.setTotalSize(resList.size());
        return result;
    }

    @Override
    public ListResult<RRoomDimensionScaleBean> getDimensionScaleDownList(String dimensionId, String did, String[] pids) {
        ListResult<RRoomDimensionScaleBean> result = new ListResult<RRoomDimensionScaleBean>();
        List<RRoomDimensionScaleBean> resList = roomImpl.getDimensionScaleDownList(dimensionId, did, pids);
//        List<RRoomDimensionScaleBean> resList = new ArrayList<RRoomDimensionScaleBean>();
//        if (lists != null) {
//            RRoomDimensionScaleBean rar = null;
//            for (RoomDimensionScaleBean res : lists) {
//                rar = new RRoomDimensionScaleBean();

//                BeanUtils.copyProperties(res, rar);
//                rar.setCreateTime(DateTimeUtil.formatTimestamp(res.getCreateTime()));
//                resList.add(rar);
//            }
//        }
        result.setData(resList);
        result.setTotalSize(resList.size());
        return result;
    }

    @Override
    public ListResult<RRoomDimensionScaleListBean> getDimensionScaleList() {
        ListResult<RRoomDimensionScaleListBean> result = new ListResult<RRoomDimensionScaleListBean>();
        List<RRoomDimensionScaleListBean> resList = roomImpl.getDimensionScaleList();
        result.setData(resList);
        result.setTotalSize(resList.size());
        return result;
    }

    @Override
    public RoomDimensionDetailBean editDimensionDetail(AccountBean account, RoomDimensionDetailBean data) {
        boolean flag = false;
        if (StringUtil.isEmpty(data.getDid())) {
            // 判断属性是否已经存在
            if (roomImpl.selectDimensionDetailByName(data.getDimensionId(), data.getName()) != null) {
                throw new ServiceException("object_is_exist","影厅维度详情信息");
            }
            data.setAccountId(account.getAccid());
            data.setDid(AppTextUtil.getPrimaryKey());
            flag = roomImpl.insertDimensionDetail(data) > 0;
            if (!flag) {
                throw new ServiceException("database_insert_fail","影厅维度详情信息");
            }
        } else {
            if (roomImpl.selectDimensionDetailById(data.getDid()) == null){
                throw new ServiceException("object_is_not_exist","影厅维度详情信息");
            }
            flag = roomImpl.updateDimensionDetail(data) > 0;// 更新数据库
            if (!flag) {
                throw new ServiceException("database_update_fail","影厅维度详情信息");
            }
        }

        RoomDimensionDetailBean res = new RoomDimensionDetailBean();
        BeanUtils.copyProperties(roomImpl.selectDimensionDetailById(data.getDid()), res);
        return res;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean delDimensionDetail(AccountBean account, String id) {
        boolean flag = false;
		// 删除
		RoomDimensionDetailBean data = roomImpl.selectDimensionDetailById(id);
		if(data == null) {
            throw new ServiceException("object_is_not_exist", "影厅维度详情信息");
        } else {
			flag = roomImpl.delDimensionDetail(id) > 0;
			if(!flag) {
				throw new ServiceException("database_delete_fail","影厅维度详情信息");
			}
		}

		return flag;
    }

    @Override
    public RoomDimensionScaleBean editDimensionScale(AccountBean account, RoomDimensionScaleBean data) {
        boolean flag = false;
        if (StringUtil.isEmpty(data.getSid())) {
            // 先判断是否已经存在对应的组合
            RoomDimensionScaleBean bean = roomImpl.selectDimensionScaleByDims(data.getDimeRalation());
            if (bean != null) {
                throw new ServiceException("object_is_exist", "此影厅维度组合");
            }
            data.setAccountId(account.getAccid());
            data.setSid(AppTextUtil.getPrimaryKey());
            flag = roomImpl.insertDimensionScale(data) > 0;
            if (!flag) {
                throw new ServiceException("database_insert_fail","影厅维度组合信息");
            }
        } else {
            RoomDimensionScaleBean bean = roomImpl.selectDimensionScaleById(data.getSid());
            if (bean == null){
                throw new ServiceException("object_is_not_exist","影厅维度组合信息");
            }
            // 判断是否需要修改组合信息，只有组合长度变化才需要修改
            if (bean.getDimeRalation().split(",").length==data.getDimeRalation().split(",").length) {
                data.setDimeRalation(null);
            }
            flag = roomImpl.updateDimensionScale(data) > 0;// 更新数据库
            if (!flag) {
                throw new ServiceException("database_update_fail","影厅维度组合信息");
            }
        }
        RoomDimensionScaleBean res = new RoomDimensionScaleBean();
        BeanUtils.copyProperties(roomImpl.selectDimensionScaleById(data.getSid()), res);
        return res;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean delDimensionScale(AccountBean account, String id) {
        boolean flag = false;
		// 删除
		RoomDimensionScaleBean data = roomImpl.selectDimensionScaleById(id);
		if(data == null) {
            throw new ServiceException("object_is_not_exist", "影厅维度组合信息");
        } else {
			flag = roomImpl.delDimensionScale(id) > 0;
			if(!flag) {
				throw new ServiceException("database_delete_fail","影厅维度组合信息");
			}
		}

		return flag;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public RoomBean editRoom(AccountBean account, RoomBean data, String scale) {
        boolean flag = false;
        // 验证组合类型是否存在
        RoomDimensionScaleBean sbean = roomImpl.selectDimensionScaleByDims(scale);
        if (sbean == null) {
            throw new ServiceException("object_is_not_exist", "当前选中的影厅维度组合");
        }
        String[] scales = sbean.getDimeRalation().replaceAll("['|\\[|\\]]", "").split(",");
        if (StringUtil.isEmpty(data.getRid())) {
            data.setAccountId(account.getAccid());
            data.setStatus(1);
            data.setRid(AppTextUtil.getPrimaryKey());
            flag = roomImpl.insertRoom(data, scales) > 0;
            if (!flag) {
                throw new ServiceException("database_insert_fail","影厅");
            }
            // 添加价格
            roomImpl.addRoomPriceByDime(data.getRid(), sbean.getSid());
        } else {
            RoomBean bean = roomImpl.selectRoomById(data.getRid());
            if (bean == null){
                throw new ServiceException("object_is_not_exist","影厅");
            }
            flag = roomImpl.updateRoom(data, scales) > 0;// 更新数据库
            if (!flag) {
                throw new ServiceException("database_update_fail","影厅");
            }
            // 如果更新了维度组合，需要重新添加价格
            String dime = roomImpl.selectDimeRelationByRoomId(bean.getRid());
            if (!dime.equals(scale)){
                roomImpl.addRoomPriceByDime(data.getRid(), sbean.getSid());
            }
        }
        return roomImpl.selectRoomById(data.getRid());
    }

    @Override
    public ListResult<RRoomBean> getRoomList(GetRoomListParam param) {
        ListResult<RRoomBean> result = new ListResult<RRoomBean>();
        List<RRoomBean> resList = roomImpl.getRoomList(null, param.getNo(), param.getName(), param.getScale(), param.getPage(), param.getPageSize());
        result.setData(resList);
        result.setTotalSize(resList.size());
        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean delRoom(AccountBean account, String id) {
        boolean flag = false;
		// 删除
		RoomBean data = roomImpl.selectRoomById(id);
		if(data == null) {
            throw new ServiceException("object_is_not_exist", "影厅");
        } else {
		    //TODO 先判断当前 影厅是否设置价格，以及是否有订单存在
            // 确认完之后才可以删除

			flag = roomImpl.delRoom(id) > 0;
			if(!flag) {
				throw new ServiceException("database_delete_fail","影厅");
			}
		}
		return flag;
    }


    @Override
    public ListResult<RTimeBucketBean> getTimeBucketList() {
        ListResult<RTimeBucketBean> result = new ListResult<RTimeBucketBean>();
        List<RTimeBucketBean> resList = roomImpl.getTimeBucketList();
        result.setData(resList);
        result.setTotalSize(resList.size());
        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public RTimeBucketBean addTimeBucket(AccountBean account, TimeBucketBean data, String buckets) {
        // 先判断名字是否重复
        RTimeBucketBean bean = roomImpl.selectTimeBucketByName(data.getName());
        if (bean != null) {
            throw new ServiceException("object_is_exist", "名字为"+data.getName()+"的时间段");
        }

        boolean flag = false;
        data.setAccountId(account.getAccid());
        data.setStatus(1);
        String lasttime = "";
        String[] lastArr;
        String[] currArr;
        // ["00:00","09:00"],["09:01","23:59"]
        String[] bucketArr = buckets.replaceAll("\\],\\[","-").replaceAll("\\[|\\]|\"", "").split("-");
        List<Map<String, String>> list = new ArrayList<>();
        for (String item : bucketArr) {
            String[] it = item.split(",");
            if (!lasttime.equals("")) {
                // 判断时间连续性
//                if (!lasttime.equals(it[0])) {
//                    throw new ServiceException("database_insert_fail", it[0]+"和"+lasttime+"时间段不连续");
//                }
                lastArr = lasttime.split(":");
                currArr = it[0].split(":");
                if (currArr[1].equals("00")) currArr[1] = "60";
                if (NumUtil.toInt(currArr[1], 9)- NumUtil.toInt(lastArr[1], 0) != 1) {
                    throw new ServiceException("database_insert_fail", it[0]+"和"+lasttime+"时间段不连续");
                } else {
                    if (lastArr[1].equals("59") && NumUtil.toInt(currArr[0], 9)-NumUtil.toInt(lastArr[0], 0)!=1) {
                        throw new ServiceException("database_insert_fail", it[0]+"和"+lasttime+"时间段不连续");
                    }
                    if (!lastArr[1].equals("59") && !currArr[0].equals(lastArr[0])) {
                        throw new ServiceException("database_insert_fail", it[0]+"和"+lasttime+"时间段不连续");
                    }
                }
            }
            Map<String, String> m = new HashMap<>();
            m.put("startTime", it[0]);
            m.put("endTime", it[1]);
            m.put("id", AppTextUtil.getPrimaryKey());
            list.add(m);
            lasttime = it[1];
        }
        flag = roomImpl.addTimeBucket(data, list) > 0;
        if (!flag) {
            throw new ServiceException("database_insert_fail","时间段");
        }
        return roomImpl.selectTimeBucketByName(data.getName());
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean delTimeBucket(AccountBean account, String name) {
        boolean flag = false;
		// 删除
        RTimeBucketBean bean = roomImpl.selectTimeBucketByName(name);
        if (bean == null) {
            throw new ServiceException("object_is_not_exist", "名字为"+name+"的时间段");
        } else {
            if (roomImpl.countOfTimeBucketRelation(name) > 0) {
                throw new ServiceException("database_delete_fail", "名字为"+name+"的时间段已经设置了价格，无法删除");
            }
			flag = roomImpl.delTimeBucket(name) > 0;
			if(!flag) {
				throw new ServiceException("database_delete_fail","名字为"+name+"的时间段");
			}
		}
		return flag;
    }

    @Override
    public ListResult<RTimeBucketBean> getTimeBucket(AccountBean account, String name) {
        ListResult<RTimeBucketBean> result = new ListResult<RTimeBucketBean>();
        List<RTimeBucketBean> resList = roomImpl.getTimeBucket(name);
        result.setData(resList);
        result.setTotalSize(resList.size());
        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean addDimePrice(AccountBean account, RoomDimePriceBean data, String bucketName, String scales, String bucketPrices) {
        boolean flag = false;
        // 判断时间段是否存在
        List<RTimeBucketBean> list = roomImpl.getTimeBucket(bucketName);
        if (list.size() == 0) {
            throw new ServiceException("object_is_not_exist", "名字为"+bucketName+"的时间段");
        }
        // 时间段数量是否匹配
        JSONArray jsonArray = JSON.parseArray(bucketPrices);
        if (jsonArray.size() != list.size()) {
            throw new ServiceException("param_is_error", "此时间段所包含的时间段数量");
        }

        // 判断组合是否存在
        RoomDimensionScaleBean scalebean = roomImpl.selectDimensionScaleByDims(scales);
        if (scalebean == null) {
            throw new ServiceException("object_is_not_exist", "当前选中维度组合");
        }
        List<RoomDimePriceBean> rows = new ArrayList<>();

        int i = 0;
        for (RTimeBucketBean item:list) {
            Map<String, Object> map = (Map<String, Object>)jsonArray.get(i++);
            if (!item.getId().equals(map.get("id"))) {
                throw new ServiceException("param_is_error", "提交的第"+i+"个时间段数据");
            }
            for (int j = 1; j < 8; j++) {
                RoomDimePriceBean b = new RoomDimePriceBean();
                b.setCreatorId(data.getCreatorId());
                b.setDimeId(scalebean.getSid());
                b.setEndTime(data.getEndTime());
                b.setStartTime(data.getStartTime());
                b.setStatus(0);
                b.setPriceType(data.getPriceType()==5 ? 5 : 0);
                b.setBucketId(item.getId());
                b.setPid(AppTextUtil.getPrimaryKey());
                b.setDayOfWeek(j);
                b.setPrice(NumUtil.toDouble(map.get(""+j), -1));
                rows.add(b);
            }
        }

		flag = roomImpl.addDimePrice(rows, scales) > 0;
        if(!flag) {
            throw new ServiceException("database_insert_fail","设置价格");
        }
		return flag;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean addRoomPrice(AccountBean account, RoomPriceBean data, String bucketName, String bucketPrices) {
        boolean flag = false;
        // 判断影厅是否存在
        RoomBean room = roomImpl.selectRoomById(data.getRoomId());
        if (room == null) {
            throw new ServiceException("object_is_not_exist", "当前影厅");
        }
        // 判断时间段是否存在
        List<RTimeBucketBean> list = roomImpl.getTimeBucket(bucketName);
        if (list.size() == 0) {
            throw new ServiceException("object_is_not_exist", "名字为"+bucketName+"的时间段");
        }
        // 时间段数量是否匹配
        JSONArray jsonArray = JSON.parseArray(bucketPrices);
        if (jsonArray.size() != list.size()) {
            throw new ServiceException("param_is_error", "此时间段所包含的时间段数量");
        }

        List<RoomPriceBean> rows = new ArrayList<>();

        int i = 0;
        for (RTimeBucketBean item:list) {
            Map<String, Object> map = (Map<String, Object>)jsonArray.get(i++);
            if (!item.getId().equals(map.get("id"))) {
                throw new ServiceException("param_is_error", "提交的第"+i+"个时间段数据");
            }
            for (int j = 1; j < 8; j++) {
                RoomPriceBean b = new RoomPriceBean();
                b.setCreatorId(data.getCreatorId());
                b.setRoomId(data.getRoomId());
                b.setEndTime(data.getEndTime());
                b.setStartTime(data.getStartTime());
                b.setStatus(0);
                b.setPriceType(data.getPriceType()==5 ? 5 : 0);
                b.setBucketId(item.getId());
                b.setPid(AppTextUtil.getPrimaryKey());
                b.setDayOfWeek(j);
                b.setPrice(NumUtil.toDouble(map.get(""+j), -1));
                rows.add(b);
            }
        }

		flag = roomImpl.addRoomPrice(rows) > 0;
        if(!flag) {
            throw new ServiceException("database_insert_fail","设置价格");
        }
		return flag;
    }

    @Override
    public ListResult<RRoomPriceBean> getRoomPriceList(AccountBean account, String id, Integer page, Integer pageSize) {
        ListResult<RRoomPriceBean> result = new ListResult<RRoomPriceBean>();
        List<RRoomPriceBean> resList = roomImpl.getRoomPriceList(id, page, pageSize);
        result.setData(resList);
        result.setTotalSize(resList.size());
        return result;
    }

    @Override
    public ListResult<RRoomPriceBean> getRoomPriceDetail(AccountBean account, GetRoomPriceDetailParam param) {
        ListResult<RRoomPriceBean> result = new ListResult<RRoomPriceBean>();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("name", param.getName());
        params.put("id", param.getId());
        params.put("startTime", param.getStartTime());
        params.put("endTime", param.getEndTime());
        params.put("createTime", param.getCreateTime());
        params.put("priceType", param.getPriceType().equals("5") ? "5" : "0");
        List<RRoomPriceBean> resList = roomImpl.getRoomPriceDetail(params);
        result.setData(resList);
        result.setTotalSize(resList.size());
        return result;
    }

    @Override
    public ListResult<RRoomMonthPriceBean> getRoomMonthPrice(AccountBean account, GetRoomMonthPriceParam param) {
        ListResult<RRoomMonthPriceBean> result = new ListResult<RRoomMonthPriceBean>();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("id", param.getId());
        params.put("date", param.getDate());
        List<RRoomMonthPriceBean> resList = roomImpl.getRoomMonthPrice(params);
        result.setData(resList);
        result.setTotalSize(resList.size());
        return result;
    }

    @Override
    public ListResult<RRoomPriceBean> getRoomCurrPrice(AccountBean account, String id) {
        ListResult<RRoomPriceBean> result = new ListResult<RRoomPriceBean>();
        List<RRoomPriceBean> resList = roomImpl.getRoomCurrPrice(id);
        result.setData(resList);
        result.setTotalSize(resList.size());
        return result;
    }

    @Override
    public RRoomBean getRoomById(String id) {
        List<RRoomBean> list = roomImpl.getRoomList(id, "", "", "",0, 1);
        if (list.size() == 0) {
            throw new ServiceException("object_is_not_exist","影厅信息");
        }
        return list.get(0);
    }


    @Override
    public ListResult<RDimePriceBean> getDimePriceList(AccountBean account, String dateB, String dateE, Integer priceType, String scale, Integer page, Integer pageSize) {
        ListResult<RDimePriceBean> result = new ListResult<RDimePriceBean>();
        List<RDimePriceBean> resList = roomImpl.getDimePriceList(dateB, dateE, priceType, scale, page, pageSize);
        result.setData(resList);
        result.setTotalSize(resList.size());
        return result;
    }

    @Override
    public ListResult<RDimePriceBean> getDimePriceDetail(AccountBean account, GetDimePriceDetailParam param) {
        ListResult<RDimePriceBean> result = new ListResult<RDimePriceBean>();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("name", param.getName());
        params.put("id", param.getId());
        params.put("startTime", param.getStartTime());
        params.put("endTime", param.getEndTime());
        params.put("createTime", param.getCreateTime());
        params.put("priceType", "0");
        List<RDimePriceBean> resList = roomImpl.getDimePriceDetail(params);
        result.setData(resList);
        result.setTotalSize(resList.size());
        return result;
    }
}
